package com.ewhome.apartment.mvp.model;

import android.app.Application;

import com.ewhome.apartment.app.GlobalHttpHandlerImpl;
import com.ewhome.apartment.app.constant.AppConstant;
import com.ewhome.apartment.mvp.model.api.service.UserService;
import com.ewhome.apartment.mvp.model.entity.BaseData;
import com.ewhome.apartment.mvp.model.entity.res.ResApiBean;
import com.ewhome.apartment.mvp.model.entity.res.ResHomeBean;
import com.google.gson.Gson;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.mvp.BaseModel;

import com.jess.arms.di.scope.ActivityScope;

import javax.inject.Inject;

import com.ewhome.apartment.mvp.contract.HomeContract;

import io.reactivex.Observable;
import io.reactivex.functions.Function;


@ActivityScope
public class HomeModel extends BaseModel implements HomeContract.Model {
    private Gson mGson;
    private Application mApplication;
    private UserService service;
    private ResApiBean apicache;
    @Inject
    public HomeModel(IRepositoryManager repositoryManager, Gson gson, Application application,Cache<String, Object> extracache) {
        super(repositoryManager);
        this.mGson = gson;
        this.mApplication = application;
        this.service=repositoryManager.obtainRetrofitService(UserService.class);
        this.apicache= (ResApiBean) extracache.get(AppConstant.API_CACHE);
    }

    @Override
    public Observable<ResHomeBean> getHomedata() {
        return service.requestWithoutbody(apicache.getRoom().getUrl())
                .map(new Function<BaseData, ResHomeBean>() {
                    @Override
                    public ResHomeBean apply(BaseData baseData) throws Exception {
                        String data= GlobalHttpHandlerImpl.decodeFromJNI(baseData.getCipher());
                        return mGson.fromJson(data,ResHomeBean.class);
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mGson = null;
        this.mApplication = null;
    }

}